import { ref } from 'vue'
import store from '@/store'
import router from "@/router"
import { storage } from '@/utils/Storage'
import { ACCESS_TOKEN } from '@/store/mutation-types'
import { login as _login, logout as _logout } from '@/api/user'
import { CODEENUM } from '@/config'
import { message } from "ant-design-vue";

export default function useUser() {
  const loginLoading = ref(false)

  /**
   * 用户登录
   * @param {*} params 
   * @returns 
   */
  const login = async (params) => {
    loginLoading.value = true
    const { data, code, msg } = await _login(params)
    if (code !== CODEENUM.OP_SUCCESS) return message.error(msg || '登录失败')
    message.success(msg || '登录成功')
    // 设置token
    setToken(data.token)
    // 保存用户信息
    setUserInfo(data.user)
    setTimeout(() => {
      loginLoading.value = false
      router.push({ path: `/home` })
    }, 1200)
    return { data, code, msg }
  }

  /**
   * 用户退出
   * @param {*} params 
   */
  const logout = async () => {
    const { data, code, msg } = await _logout()
    if (code !== CODEENUM.OP_SUCCESS) return message.error(msg || '登出失败')
    message.success(msg || '登出成功')
    clearAll()
    setTimeout(() => {
      router.replace({ path: `/login` })
    }, 1200)
  }

  /**
   * 设置token
   */
  const setToken = (token) => {
    store.commit('CHANGE_SETTING', { key: 'token', value: token })
    storage.set(ACCESS_TOKEN, token)
  }

  /**
   * 获取token
   */
  const getToken = () => {
    return store.getters.token || storage.set(ACCESS_TOKEN)
  }

  /**
   * 设置userInfo
   */
  const setUserInfo = (userInfo) => {
    store.commit('CHANGE_SETTING', { key: 'userInfo', value: userInfo })
    storage.set('userInfo', userInfo)
  }

  /**
   * 获取userInfo
   */
  const getUserInfo = () => {
    return store.getters.userInfo || storage.get('userInfo')
  }

  /**
   * 清除保存的所有信息
   */
  const clearAll = () => {
    storage.clear()
    store.commit('RESET_STATE')
  }

  return {
    loginLoading,
    login,
    logout,
    setToken,
    getToken,
    setUserInfo,
    getUserInfo,
  }
}